package com.lhkj.ct.meta.modules.report.word;

import com.google.common.collect.Lists;
import com.lhkj.ct.base.utils.chart.JFreeChartConfig;
import com.lhkj.ct.base.utils.chart.JFreeChartUtil;
import com.lhkj.ct.base.utils.file.word.xwpf.CustomXWPFDocument;
import com.lhkj.ct.base.utils.file.word.xwpf.ExportWord;
import com.lhkj.ct.meta.modules.gauge.common.enums.QuestionType;
import com.lhkj.ct.meta.modules.questionnaire.model.vo.QuestionnaireStatisticsVo;
import com.lhkj.ct.meta.modules.report.AbstractReportHandle;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STPageOrientation;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
public class QuestionnaireStatisticsReportHandle extends AbstractReportHandle<QuestionnaireStatisticsVo, XWPFDocument> {

    private final ExportWord word;

    public QuestionnaireStatisticsReportHandle() {
        word = new ExportWord();
    }

    @Override
    public XWPFDocument generateReport(QuestionnaireStatisticsVo data) {

        CustomXWPFDocument document = new CustomXWPFDocument();
        // 设置word页面大小
        word.setPageSize(document,19000L, 25000L, STPageOrientation.PORTRAIT);
        // step 1.标题
        generateTitle(document, data);
        // step 2.统计图表
        drawChart(document, data);
        // step 3.题目
        questionTable(document, data.getQuestions());
        return document;
    }

    /**
     * TODO 报告标题
     */
    private void generateTitle(XWPFDocument document, QuestionnaireStatisticsVo data) {
        // step 1.标题
        XWPFParagraph titlePara = document.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = titlePara.createRun();
        run.setText(data.getQnrName());
        run.setFontFamily("宋体");
        run.setFontSize(14);
        run.setBold(true);
        run.addBreak();
        XWPFRun run1 = titlePara.createRun();
        run1.setFontFamily("宋体");
        run1.setFontSize(12);
        run1.setText("答卷共计" + data.getTotal() + "份 ，总平均分：" + data.getTotalAvg() + "分。");
        run1.addBreak();
        XWPFRun run2 = titlePara.createRun();
        run2.setFontFamily("宋体");
        run2.setFontSize(12);
        run2.setText("（注：填空题和简答题不参与统计分析）");
        run2.addBreak();
    }

    /**
     * TODO 统计图表
     */
    private void drawChart(CustomXWPFDocument document, QuestionnaireStatisticsVo data) {

        XWPFParagraph picturePara = document.createParagraph();
        // 设置为两边对齐
        picturePara.setAlignment(ParagraphAlignment.DISTRIBUTE);
        // 绘制男女比例饼图
        try {
            JFreeChartConfig pieConfig = new JFreeChartConfig();
            pieConfig.setTitle("男女比例");
            pieConfig.setWidth(522);
            pieConfig.setHeight(480);

            DefaultPieDataset pieDataset = new DefaultPieDataset();
            for (QuestionnaireStatisticsVo.SexRatio sexRatio : data.getSexRatios()) {
                pieDataset.setValue(sexRatio.getName(), sexRatio.getValue());
            }

            BufferedImage bi = JFreeChartUtil.drawPieChart(pieConfig, pieDataset);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", os);
            picturePara.createRun().addPicture(new ByteArrayInputStream(os.toByteArray()), XWPFDocument.PICTURE_TYPE_JPEG, "",
                    Units.pixelToEMU(325), Units.pixelToEMU(300));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 绘制年龄比例柱状图
        try {
            JFreeChartConfig pieConfig = new JFreeChartConfig();
            pieConfig.setWidth(800);
            pieConfig.setHeight(400);
            pieConfig.setTitle("年龄比例");
            DefaultCategoryDataset ageDataset = new DefaultCategoryDataset();
            for (QuestionnaireStatisticsVo.AgeRatio ageRatio : data.getAgeRatios()) {
                ageDataset.addValue(ageRatio.getValue(), "年龄段", ageRatio.getName());
            }
            BufferedImage bi = JFreeChartUtil.drawVerticalBarChart(pieConfig, ageDataset);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", os);
            picturePara.createRun().addPicture(new ByteArrayInputStream(os.toByteArray()), XWPFDocument.PICTURE_TYPE_JPEG, "",
                    Units.pixelToEMU(600), Units.pixelToEMU(300));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 换行
        picturePara.createRun().addBreak();
    }

    /**
     * TODO 题目
     */
    private void questionTable(XWPFDocument document, List<QuestionnaireStatisticsVo.Question> questions){
        for (QuestionnaireStatisticsVo.Question question : questions) {
            XWPFParagraph tmPara = document.createParagraph();
            String text = question.getQutTitle();
            if (question.getType() == QuestionType.radio || question.getType() == QuestionType.checkbox) {
                text += "（本题平均分" + question.getAvg() + "分）";
            }
            XWPFRun run3 = tmPara.createRun();
            run3.setFontFamily("宋体");
            run3.setFontSize(14);
            run3.setBold(true);
            run3.setText(text);
            if (question.getType() == QuestionType.text) {
                run3.setText("______");
            }
            if (question.getType() == QuestionType.radio || question.getType() == QuestionType.checkbox) {
                XWPFTable table = document.createTable(1, 3);
                table.setWidth("100%");
                word.getXwpfTableHelper().setTableRowStyle(table, 0, "7CB5EC", XWPFTableCell.XWPFVertAlign.CENTER, STJc.CENTER);
                table.getRow(0).getCell(0).setText("选项");
                table.getRow(0).getCell(1).setText("小计");
                table.getRow(0).getCell(2).setText("比例");
                List<List<Object>> collect = question.getOptions().stream().map(p -> Lists.newArrayList(p.getOptTitle(), (Object) p.getSubtotal(), p.getPercent())).collect(Collectors.toList());
                word.insertTable(table, collect, STJc.CENTER, STVerticalJc.CENTER);
                XWPFTableRow row = table.createRow();
                word.getXwpfTableHelper().mergeCellsHorizontal(table, table.getRows().size() - 1, 0, 2);
                table.getRow(table.getRows().size() - 1).getCell(0).setText("本题作答人数："+ question.getCounts());
                row.getCell(0).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                word.getXwpfTableHelper().setTableRowsHeight(table, 600, null);
                document.createParagraph().createRun().addBreak();
            }
            if (question.getType() != QuestionType.radio && question.getType() != QuestionType.checkbox) {
                tmPara.createRun().addBreak();
            }
        }
    }
}
